package com.chang.soul.controller;

import com.chang.soul.bean.Audience;
import com.chang.soul.bean.UserBean;
import com.chang.soul.exception.ResultCode;
import com.chang.soul.service.ArticleService;
import com.chang.soul.service.UserService;
import com.chang.soul.conf.JwtIgnore;
import com.chang.soul.util.JwtTokenUtil;
import com.chang.soul.util.Result;
import com.chang.soul.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;



/**
 * @author xiaoqingyang@vip.henu.edu.cn
 * @date 2021/3/31 20:49
 */

/* @RestController = @Controller + @ResponseBody
*  @Controller 将当前修饰的类注入SpringBoot IOC容器，使得从该类所在的项目跑起来的过程中，这个类就被实例化
*  @ResponseBody 指该类中所有的API接口返回的数据，甭管你对应的方法返回Map或是其他Object，它会以Json字符串的形式返回给客户端
* */
@RestController
/*@RequestMapping 将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。用来进行 Spring MVC 控制器方法的映射 */
@RequestMapping("/user")
/*Swagger是当前最好用的Restful API文档生成的开源项目*/
/*@Api：修饰整个类，描述Controller的作用*/
@Api("用户管理接口")
public class UserController {

    /*@Autowired是用在JavaBean中的注解，通过byType形式，用来给指定的字段或方法注入所需的外部资源。*/
    @Autowired
    UserService userService;

    @Autowired
    private Audience audience;

    @Autowired
    private ArticleService articleService;

    private static Logger log =  LoggerFactory.getLogger(UserController.class);
    /*@ApiOperation：描述一个类的一个方法，或者说一个接口*/
    @ApiOperation(value = "查询所有用户", notes = "测试用", httpMethod = "GET")
    /*@GetMapping用于处理请求方法的GET类型，@ PostMapping用于处理请求方法的POST类型等。*/
    @GetMapping("/getAllUser")
    /*Json Web Token（JWT）：JSON网络令牌，是为了在网络应用环境间传递声明而制定的一种基于JSON的开放标准*/
    @JwtIgnore
    public Result getAllUser(){
        return ResultUtil.success(userService.getAllUser());
    }


    @ApiOperation(value = "登录接口",notes = "",httpMethod ="POST" )
    @PostMapping("/userLogin")
    @JwtIgnore
    public String userLogin(HttpServletResponse response, HttpServletRequest request,
                            @RequestParam(value ="nickname") String nickname,
                            @RequestParam(value = "password") String password){
        //获取用户信息
        UserBean user = userService.getUserByNickName(nickname);

        //创建用户登录信息类
        UserBean userBean = new UserBean();
        System.out.println("user"+user);

        String userId ="";
        String role = "";
        boolean loginResult = true;

        if(user== null){
            //如果是空，则返回
            loginResult =false;
        }else{
            userId =user.getId()+"";
            role = "user";
            loginResult = user.getPassword().equals(password);
        }
        if(loginResult){
            //创建Token
            String token = JwtTokenUtil.createJWT(userId,nickname,role,audience);
            log.info("### 登录成功，userName={} ###",user.getRealName());

            // 将token放在相应头
            response.setHeader(JwtTokenUtil.AUTH_HEADER_KEY,JwtTokenUtil.TOKEN_PREFIX+token);
            //将token 相应给客户端
            JSONObject result = new JSONObject();
            result.put("status", ResultCode.SUCCESS);
            result.put("statusCode",ResultCode.SUCCESS.code());
            result.put("describe",ResultCode.SUCCESS.message());

            JSONObject object = new JSONObject();
            object.put("user",user);
            result.put("datas",object);
            object.put("token","zswlsjpd"+token);
            System.out.println("zswlsjpd"+token+" -----登录返回token-----");
            return result.toJSONString();

        }else {
            log.info("### 登录失败, IP={} ###", request.getRequestURL());
            JSONObject result = new JSONObject();
            result.put("status", ResultCode.FAIL);
            result.put("statusCode", ResultCode.FAIL.code());
            result.put("describe", ResultCode.FAIL.message());
            JSONObject object = new JSONObject();
            object.put("token", "");
            result.put("datas", object);
            return result.toJSONString();
        }
    }


    @ApiOperation(value = "添加用户接口",notes = "", httpMethod = "POST")
    @PostMapping("/insertUser")
    @JwtIgnore
    /*@Valid 注解通常用于对象属性字段的规则检测*/
    public Result insertUser(@Valid @RequestBody UserBean userBean){
        boolean insert_flag = false;
        int counts = userService.getCountsByNickName(userBean.getNickName());
        if(counts<1){
            insert_flag = userService.insertUser(userBean);
            if(insert_flag){
                return ResultUtil.success(userBean);
            }else{
                return ResultUtil.error("insert fail");
            }
        }else {
            return ResultUtil.error("用户昵称已经存在");
        }
    }

    @ApiOperation(value = "删除用户接口",notes = "",httpMethod = "GET")
    @GetMapping("/deleteUserById")
    @JwtIgnore
    public Result deleteUserById(@RequestParam(value = "id")Integer id){
        boolean delete_flag = userService.deleteUserById(id);
        if(!delete_flag){
            return ResultUtil.error("delete user fail");
        }
        return ResultUtil.success("delete user success");
    }

    @ApiOperation(value = "用户信息更新接口",notes = "",httpMethod = "POST")
    @PostMapping("/updateUser")
    @JwtIgnore
    public Result updateUser(@Valid @RequestBody UserBean myUserBean){

        UserBean userBean = userService.getUserById(myUserBean.getId()) ;
        String Password = myUserBean.getPassword();
        System.out.println("Password: "+Password);
        if(Password!= null ){
            userBean.setPassword(Password);
        }
        userBean.setNickName(myUserBean.getNickName());
        userBean.setGender(myUserBean.getGender());
        userBean.setAge(myUserBean.getAge());
        userBean.setPassword(myUserBean.getPassword());

        userBean.setBrief(myUserBean.getBrief());

        if(userService.updateUser(userBean)){
            return ResultUtil.success(userBean);
        }else{
            return ResultUtil.error("update user information fail");
        }
    }
}
